package javalight.network.ro.client;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketException;
import javalight.network.ro.DataObject;
import javalight.network.ro.jsonImpl.DataObjectImpl;

public class RemoteObject {

	private String remoteClassName;
	DatagramSocket client;
	DatagramPacket data;
	
	public RemoteObject(String remoteClassName, String remoteHost, int remotePort) throws RemoteException
	{
		this.remoteClassName = remoteClassName;
		try {
			client = new DatagramSocket();
			byte[] buf = new byte[1024*10];
			data = new DatagramPacket(buf, buf.length, new InetSocketAddress(remoteHost, remotePort));
		} catch (SocketException e) {
			throw new RemoteException("Initial Error. ", e);
		}
	}
	
	public DataObject invokeMethod(String methodName, Object... params) throws RemoteException
	{
		DataObject doo = new DataObjectImpl();
		doo.set("class", remoteClassName);
		doo.set("method", methodName);
		doo.set("params", params);
		try {
			data.setData(doo.toString().getBytes("utf-8"));
			client.send(data);
			client.receive(data);
			String callback = new String(data.getData(), 0, data.getLength(), "utf-8");
			System.out.println(callback);
			DataObject back = new DataObjectImpl(callback);
			while(!"success".equals(back.get("response")))
			{
				client.send(data);
				client.receive(data);
				callback = new String(data.getData(), 0, data.getLength(), "utf-8");
				back = new DataObjectImpl(callback);
			}
		} catch (UnsupportedEncodingException e) {
			throw new RemoteException(e);
		} catch (IOException e) {
			throw new RemoteException(e);
		}
		return null;
	}
	
	private boolean checkFormat(DataObject recv)
	{
		
		return true;
	}
	
	
	public static void main(String[] args) throws Exception {
		RemoteObject obj = new RemoteObject("class java", "localhost", 10190);
		obj.invokeMethod("say", "hello");
		obj.invokeMethod("say", "hello2");
		obj.invokeMethod("say", "hello3");

	}

}
